﻿using UnityEngine;
using System.Collections.Generic;

public class InitiativeManager : Singleton<InitiativeManager>
{
	public delegate void Callback();
	public static Callback characterChanged;
	public static Callback characterAdded;
	
	public Character current = null;
	public Character next = null;
	public List<Character> characters = new List<Character>();

	public void RegisterCharacter(Character _character)
	{
		if (!characters.Contains(_character))
		{
			characters.Add(_character);
			OrderByInitiative();
			next = characters[(characters.IndexOf(current) + 1) % characters.Count];

			if (current == null)
			{
				NextCharacter();
				HUDScreen.Instance.SetupCharacter(_character);
				GameCamera.Instance.MoveCamera(_character);
			}

			if (characterAdded != null)
			{
				characterAdded();
			}
		}
	}

	public void NextCharacter()
	{
		current = characters[(characters.IndexOf(current) + 1) % characters.Count];
		next = characters[(characters.IndexOf(current) + 1) % characters.Count];

		if (characterChanged != null)
		{
			characterChanged();
		}

		Debug.Log("Current Player " + current);
		Invoke("StartCharacterTurn", 0.5f);
	}

	private void StartCharacterTurn()
	{
		current.StartTurn();
	}

	private void OrderByInitiative()
	{
		CharacterInfo info1;
		CharacterInfo info2;
		bool inOrder = false;
		while (!inOrder)
		{
			inOrder = true;
			for (int i = 0; i < characters.Count - 1; i++)
			{
				info1 = characters[i].GetInfo<CharacterInfo>();
				info2 = characters[i + 1].GetInfo<CharacterInfo>();
				if (info1.initiative.GetValue() < info2.initiative.GetValue())
				{
					Character temp = characters[i];
					characters[i] = characters[i + 1];
					characters[i + 1] = temp;
					inOrder = false;
				}
			}
		}
	}

	public List<Player> GetAllPlayers()
	{
		List<Player> players = new List<Player>();
		foreach (Character c in characters)
		{
			if (c is Player)
			{
				players.Add(c as Player);
			}
		}

		return players;
	}
}
